package com.game.core.dbwrite.util;

import java.util.ArrayList;

import org.rocksdb.Comparator;
import org.rocksdb.ComparatorOptions;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.Slice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.core.dbwrite.domain.StoreEntity;

public class RocksDBUtil
{
	private static final Logger logger = LoggerFactory.getLogger(RocksDB.class);

	public static RocksDB openRocksDB(String dbPath)
	{
		RocksDB.loadLibrary();
		Options options = new Options().setCreateIfMissing(true);
		ComparatorOptions compartorOptions = new ComparatorOptions();
		options.setComparator(new Comparator(compartorOptions)
		{
			@Override
			public int compare(Slice a, Slice b)
			{
				int aValue = Integer.parseInt(a.toString());
				int bValue = Integer.parseInt(b.toString());
				return aValue - bValue;
			}

			@Override
			public String name()
			{
				return "leveldb.BytewiseComparator";
			}
		});
		RocksDB db = null;
		try
		{
			db = RocksDB.open(options, dbPath);
		}
		catch (RocksDBException e)
		{
			logger.error("open RocksDB failed.", e);
//			e.printStackTrace();
		}
		catch (Exception e)
		{
			logger.error("open RocksDB failed.", e);
//			e.printStackTrace();
		}
		return db;
	}

	public static void addKeyToRocksDB(RocksDB db, byte[] key, byte[] value)
	{
		if (db != null)
		{
			try
			{
				db.put(key, value);
				logger.info("put key-value to RocksDB successfully.");
			}
			catch (RocksDBException e)
			{
				logger.debug("put key-value to RocksDB error.",e);
//				e.printStackTrace();
			}
			catch (Exception e)
			{
//				e.printStackTrace();
				logger.debug("put key-value to RocksDB error.",e);
			}
		}
		else
		{
			logger.info("RocksDB is null.");
		}
	}

	public static ArrayList<StoreEntity> getKeysFromRocksDB(RocksDB db)
	{
		ArrayList<StoreEntity> list = new ArrayList<StoreEntity>();
		if (db != null)
		{
			RocksIterator iter = db.newIterator();
			for (iter.seekToFirst(); iter.isValid(); iter.next())
			{
				logger.info("******************************RocksDB Key******************************: " + new String(iter.key()));
				list.add((StoreEntity) KryoUtil.deSerilize(StoreEntity.class, iter.value()));
				try
				{
					db.remove(iter.key());
				}
				catch (RocksDBException e)
				{
					logger.debug("RocksDB remove key error.",e);
//					e.printStackTrace();
				}
				catch (Exception e)
				{
//					e.printStackTrace();
					logger.debug("RocksDB remove key error.",e);
				}
			}
			iter.dispose();
		}
		else
		{
			logger.info("RocksDB is null.");
		}
		return list;
	}

	public static boolean isRocksDBEmpty(RocksDB db)
	{
		boolean res = false;
		if (db != null)
		{
			RocksIterator iter = db.newIterator();
			iter.seekToFirst();
			res = !iter.isValid();
		}
		return res;
	}

	public static void closeRocksDB(RocksDB db)
	{
		if (db != null)
			db.close();
	}
}